/** @odoo-module **/

import {ControlPanel} from "@web/search/control_panel/control_panel";
import { SearchBar } from "@web/search/search_bar/search_bar";
import { SearchModel } from "@web/search/search_model";
import { Mutex } from "@web/core/utils/concurrency";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { download } from "@web/core/network/download";
import { Component, onWillStart, onMounted, useChildSubEnv, useState, useRef, useSubEnv} from "@odoo/owl";
// import { MrpProductionTaskModel } from '@sb_plan/models/mrp_task_model';
const { DateTime } = luxon;

export class SMrpSchedulingComponent extends Component {
    setup() {
        this.action = useService("action");
        this.dialog = useService("dialog");
        this.orm = useService("orm");
        this.viewService = useService("view");
        this.rpc = useService("rpc");
        this.mutex = new Mutex();
        const { orm, action, dialog } = this;
        // this.model = new MrpProductionTaskModel(this.props, { orm, action, dialog });
        this.state = useState({
            dateList: [],
            toDay: DateTime.now().toFormat("yyyy-MM-dd"),
            dateStr: '',
        });

        this.stationLabel = useState([]);
        this.lines = useState([]);
        this.total = useState([]);
        this.searchInput = useRef('input')

        onWillStart(async () => {


        });
        onMounted(async () => {
            await this.getWorkLabel();
            await this.getTaskLine();
            this.getDate()
        })
    }

    getToDay() {
        const now = DateTime.utc();
        const cutoff = now.set({hour: 1, minute: 30, second: 0, millisecond: 0});
        return (now < cutoff
                ? now.minus({days: 1})
                : now
        ).toFormat('yyyy-MM-dd');
    }

    getDate() {
        this.state.toDay = this.getToDay();
        // 设置基准日期，用于限制最小日期
        this.state.baseDate = this.state.toDay;
    }

    async onTodayClicked() {
        this.state.toDay = this.getToDay();
        await this.getTaskLine()
    }

    async onPreviousPeriodClicked() {
        const currentDate = DateTime.fromISO(this.state.toDay, { zone: 'utc' });
        const newDate = currentDate.minus({ days: 1 });

        // 获取当前基准日期（动态计算）
        const currentBaseDate = DateTime.fromISO(this.getToDay(), { zone: 'utc' });

        // 确保新日期不小于基准日期
        if (newDate < currentBaseDate) {
            return;
        }

        this.state.toDay = newDate.toFormat('yyyy-MM-dd');
        await this.getTaskLine()
    }

    async onNextPeriodClicked() {
        this.state.toDay = DateTime.fromISO(this.state.toDay).plus({days: 1}).toISODate();
        await this.getTaskLine()
    }

    async getWorkLabel() {
        const data = await this.orm.call(
            "s.mrp.task",
            "get_station_data",
        );
        this.stationLabel.length = 0;
        this.stationLabel.unshift(...data);

    }

    async getTaskLine(){
        const data = await this.orm.call(
            "s.mrp.task",
            "get_task_data",
            [],
            {'domain': this.getDomain(), 's_date': this.state.dateStr}
        )
        const dateList = data.date_list
        this.state.dateStr = data.s_date
        this.lines.splice(0, this.lines.length, ...data.lines);
        this.total.splice(0, this.total.length, ...data.total);
        this.state.dateList.splice(0, this.state.dateList.length, ...dateList)
    }

    _getOriginValue(production_id, station_id) {
        // 使用 find 替代 filter，直接获取第一个匹配的 line
        const line = this.lines.find(item =>
            item.production_id && item.production_id.id === production_id
        );

        if (!line) {
            return '0';
        }

        // 在 task_data 中查找对应的 task
        const task = line.task_data.find(task =>
            task.station_id && task.station_id.id === station_id
        );

        // 如果找到 task，返回 pnl；否则返回 '0'
        return task ? task.pnl.toString() : '0';
    }

    async _onChangeQty(ev, production_id, station_id) {
        const qty = ev.target.value;
        if (qty === "" || isNaN(qty)) {
            ev.target.value = this._getOriginValue(production_id, station_id);
        } else {
            await this.orm.call(
                "s.mrp.task",
                "save_production_scheduling_qty",
                [production_id,station_id,this.state.toDay,qty]
            )
            await this.getTaskLine();

        }
    }

    async onClickDateStr(dateStr) {
        this.state.dateStr = dateStr
        await this.getTaskLine()
    }

    _onClickInsertOrder(ev) {
        this.mutex.exec(() => {
            this.action.doAction('sb_plan.s_mrp_task_insert_order_wizard_action', {
                additionalContext: {date_str: this.state.dateStr},
                onClose: async () => await this.getTaskLine(),
            });
        });
    }

    async handleKeyDown(ev) {
        if (ev.key === "Enter") {
            ev.preventDefault();
            await this.getWorkLabel();
            await this.getTaskLine();
            this.getDate()
        }
    }

    getDomain() {
        if (this.searchInput.el.value) {
            const searchInput = this.searchInput.el.value.trim()
            return ['|', ['product_id.name', 'ilike', searchInput], ['production_id.name', 'ilike', searchInput]]
        } else {
            return []
        }
    }
    async onDownload() {
        const url = "/download/sb/production/wip/report/excel";
        const data = {};
        await download({ url , data });
    }

    _onFocusInput(ev) {
        ev.target.select();
    }
}

SMrpSchedulingComponent.template = "sb_plan.SMrpScheduling";
SMrpSchedulingComponent.components = {
    ControlPanel,
    // SearchBar
};
registry.category("actions").add("s_mrp_scheduling", SMrpSchedulingComponent);